import NavBar from '@/components/NavBar';
import { useAppSelector } from '@/store';
import {
  addCommentActionCreator,
  updateComm_countActionCreator,
} from '@/store/action/comment';
import { Toast } from 'antd-mobile';
import React, { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import styles from './index.module.scss';

type Props = {
  onClose: () => void;
};

export default function CommentInput({ onClose }: Props) {
  const dispatch = useDispatch();
  const { detail } = useAppSelector((state) => state.articleList);
  const [value, setValue] = useState('');
  //   console.log(11, value);

  // 发表评论
  const handleSubmit = async () => {
    if (!value) return;
    // 调用action发送异步请求，添加评论
    await dispatch(
      addCommentActionCreator({
        target: detail.art_id,
        content: value,
        art_id: detail.art_id,
      })
    );
    // 评论数量加一
    await dispatch(updateComm_countActionCreator());
    // 关闭弹窗
    onClose();
    // 提示用户
    Toast.show('评论成功');
  };

  //   输入框自动聚焦
  const txtref = useRef<HTMLTextAreaElement>(null);
  useEffect(() => {
    setTimeout(() => {
      txtref.current?.focus();
    }, 100);
  }, []);

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        right={
          <span className="publish" onClick={handleSubmit}>
            发表
          </span>
        }
        onBack={onClose}
      >
        评论文章
      </NavBar>

      <div className="input-area">
        {/* 评论内容输入框 */}
        <textarea
          ref={txtref}
          //   autoFocus
          placeholder="说点什么~"
          rows={10}
          value={value}
          onChange={(e) => setValue(e.target.value.trim())}
        />
      </div>
    </div>
  );
}
